package com.mhtube.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.mhtube.entity.po.User;
import com.mhtube.mappers.SubscribeMapper;
import com.mhtube.mappers.UserMapper;
import com.mhtube.service.UserService;
import com.mhtube.utils.DateTools;
import com.mhtube.utils.IDTools;
import com.mhtube.entity.constant.SpaceConstant;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private SubscribeMapper subscribeMapper;

    // 注册用户
    @Override
    public String registerUser(String username, String password, String email, String nikeName) {
        String id = IDTools.getRandomNums(15);
        // 检查用户ID、用户名、邮箱、昵称是否重复
        User idChecker = userMapper.selectByUserId(id);
        List<User> usernameChecker = userMapper.selectAllByUsername(username);
        List<User> emailChecker = userMapper.selectAllByEmail(email);
        List<User> nikeNameChecker = userMapper.selectAllByNikeName(nikeName);
        if(idChecker != null) {
            return "用户ID重复";
        } else if (usernameChecker.size() != 0) {
            return "用户名重复";
        } else if (emailChecker.size() != 0) {
            return "邮箱已注册";
        } else if (nikeNameChecker.size() != 0) {
            return "昵称已存在";
        }
        // 创建用户
        User user = new User();
        user.setUserId(id);
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setNikeName(nikeName);
        user.setRegisterDate(new Date());
        user.setLastLoginDate(new Date());
        user.setStatus(1);
        user.setSubscribedNum(0);
        user.setFanNum(0);
        user.setLikesNum(0);
        user.setPlayNum(0);
        user.setTotalSpace(SpaceConstant.initTotalSpace);
        user.setUsedSpace(0L);
        // 进行用户数据插入
        int result = userMapper.insertUser(user);
        if(result != 1) {
            return "注册失败";
        }
        return null;
    }

    // 登录用户
    @Override
    public boolean loginUser(HttpSession session, HttpServletResponse response, String username, String password) {
        // 从数据库种查询用户
        List<User> userList = userMapper.selectUserByUsernameAndPassword(username, password);
        if(userList.size() != 1) {
            return false;
        } else {
            // 更改最后登录时间
            String userId = userList.get(0).getUserId();
            int result = userMapper.updateLastLoginDateById(userId, new Date());
            if(result != 1) {
                return false;
            }
            // 将更新后的用户信息放入session中
            session.setAttribute("userInfo", userMapper.selectByUserId(userId));
//            //  将sessionId放在Cookie中
//            response.addCookie(new Cookie("JESSIONID", session.getId()));
            return true;
        }
    }

    // 获取用户基本信息
    @Override
    public JSONObject getBasicUserInfo(HttpSession session) {
        String userId = "";
        try {
            userId = ((User) session.getAttribute("userInfo")).getUserId();
        } catch (Exception e) {
            return null;
        }
        User user = userMapper.selectByUserId(userId);
        // 将用户基本信息放入Json中
        JSONObject result = new JSONObject();
        result.put("userId", user.getUserId());
        result.put("username", user.getUsername());
        result.put("email", user.getEmail());
        result.put("nikeName", user.getNikeName());
        result.put("registerDate", DateTools.formatDate(user.getRegisterDate()));
        result.put("lastLoginDate", DateTools.formatDate(user.getLastLoginDate()));
        result.put("status", user.getStatus());
        result.put("description", user.getDescription());
        result.put("subscribedNum", user.getSubscribedNum());
        result.put("fanNum", user.getFanNum());
        result.put("likesNum", user.getLikesNum());
        result.put("playNum", user.getPlayNum());
        result.put("totalSpace", user.getTotalSpace());
        result.put("usedSpace", user.getUsedSpace());
        return result;
    }

    // 修改个人描述
    @Override
    public boolean modifyDescription(HttpSession session, String description) {
        String userId = "";
        try {
            userId = ((User) session.getAttribute("userInfo")).getUserId();
        } catch (Exception e) {
            return false;
        }
        User userChecker = userMapper.selectByUserId(userId);
        if(userChecker == null) {
            return false;
        }
        int result = userMapper.updateDescriptionByUserId(userId, description);
        if(result != 1) {
            return false;
        }
        return true;
    }

    // 修改昵称
    @Override
    public boolean modifyNikeName(HttpSession session, String nikeName) {
        String userId = "";
        try {
            userId = ((User) session.getAttribute("userInfo")).getUserId();
        } catch (Exception e) {
            return false;
        }
        User userChecker = userMapper.selectByUserId(userId);
        if(userChecker == null) {
            return false;
        }
        int result = userMapper.updateNikeNameByUserId(userId, nikeName);
        if(result != 1) {
            return false;
        }
        return true;
    }

    // 关注用户
    @Override
    public boolean subscribeUser(HttpSession session, String subscribeAimId) {
        String userId = "";
        try {
            userId = ((User) session.getAttribute("userInfo")).getUserId();
        } catch (Exception e) {
            return false;
        }
        User userChecker = userMapper.selectByUserId(userId);
        User aimChecker = userMapper.selectByUserId(subscribeAimId);
        if(userChecker == null || aimChecker == null) {
            return false;
        }
        String subscribeId = IDTools.getRandomNums(15);
        int result = subscribeMapper.insertSubscribe(subscribeId, userId, subscribeAimId);
        if(result != 1) {
            return false;
        } else {
            return true;
        }
    }
}
